package app.project.directionlensproject.map;

import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.Date;
import java.util.Locale;

import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.GoogleMap.OnMapClickListener;
import com.google.android.gms.maps.GoogleMap.OnMarkerClickListener;
import com.google.android.gms.maps.MapFragment;
import com.google.android.gms.maps.model.BitmapDescriptorFactory;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.Marker;
import com.google.android.gms.maps.model.MarkerOptions;

import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.content.res.Configuration;
import android.database.Cursor;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.text.format.DateFormat;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnKeyListener;
import android.view.ViewTreeObserver.OnGlobalLayoutListener;
import android.view.Window;
import android.view.View.OnClickListener;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
import app.project.directionlensproject.HomeActivity;
import app.project.directionlensproject.ListPlaceActivity;
import app.project.directionlensproject.R;
import app.project.directionlensproject.compasspro.RotationVectorCompass;
import app.project.directionlensproject.fragment.FgCategory;
import app.project.directionlensproject.model.Category;
import app.project.directionlensproject.model.Place;
import app.project.directionlensproject.serverapi.ServerAPI;
import app.project.directionlensproject.util.AsyncTask;
import app.project.directionlensproject.util.BundleKeys;
import app.project.directionlensproject.util.CommonUtils;
import app.project.directionlensproject.util.Constants;
import app.project.directionlensproject.util.CustomHttpClient;
import app.project.directionlensproject.util.GPSTracker;
import app.project.directionlensproject.util.GetDataTask;
import app.project.directionlensproject.util.GoogleMapUtil;
import app.project.directionlensproject.util.IGetDataTask;
import app.project.directionlensproject.util.Utilities;

public class PlaceAddActivity extends Activity {

	private GoogleMap map;
	public static final LatLng HANOI = new LatLng(20.993776, 105.811417);
	public static final int CLICK_MARKER = 1;
	public static final int CLICK_MAP = 2;
	private static int RESULT_LOAD_IMAGE = 1;
	Place place;
	LatLng placeClick;
	MarkerOptions mkOption1;
	public String pathImage = "";
	private TextView mTextViewUser;
	private ImageView mImageViewMyPlace, mImageViewSearch;
	private EditText mEditTextSearch;
	LatLng myLocation = null;
	private ArrayList<Place> arrPlaces;
	private boolean mEditTextEnable = false;
	private boolean mIsGoogle = false;
	private Place myPlace;
	private int categoryID;
	private LinearLayout mLayoutBelow, mLayoutRoot;
	private ArrayList<Place> arrPlaceAddAvailable = new ArrayList<Place>();

	@Override
	public void onCreate(Bundle circle) {
		super.onCreate(circle);
		
		boolean isEn = CommonUtils.getBooleanSetting(this, Constants.IS_EN, false);
		if (!isEn) {
			Configuration c = new Configuration(getResources().getConfiguration());
			c.locale = new Locale("vi");
			getResources().updateConfiguration(c, getResources().getDisplayMetrics());
		} else {
			Configuration c = new Configuration(getResources().getConfiguration());
			c.locale = Locale.ENGLISH;
			getResources().updateConfiguration(c, getResources().getDisplayMetrics());
		}
		
		setContentView(R.layout.activity_place_edit);
		createViewInit();
	}

	/**
	 * create view initial
	 */
	private void createViewInit() {

		mLayoutRoot = (LinearLayout) findViewById(R.id.layoutRootView);
		String nameUser = CommonUtils.getStringSetting(PlaceAddActivity.this,
				Constants.USER_NAME, "Guest");
		mTextViewUser = (TextView) findViewById(R.id.textViewUserName);
		mTextViewUser.setText(getResources().getString(R.string.name_hello)
				+ " " + nameUser);

		mIsGoogle = getIntent().getBooleanExtra(BundleKeys.IS_GOOGLE, false);
		myPlace = (Place) getIntent().getSerializableExtra("place");
		categoryID = getIntent().getIntExtra(BundleKeys.CATE_ID, 0);
		mImageViewSearch = (ImageView) findViewById(R.id.imageViewSearchPlace);
		mEditTextSearch = (EditText) findViewById(R.id.editTextSearchPlace);
		mEditTextSearch.setOnKeyListener(searchTextListener);
		arrPlaces = new ArrayList<Place>();

		mImageViewMyPlace = (ImageView) findViewById(R.id.imageViewMyPlaceZoom);

		GPSTracker gps;
		gps = new GPSTracker(PlaceAddActivity.this);

		// check if GPS enabled
		if (gps.canGetLocation()) {
			double latitude = gps.getLatitude();
			double longitude = gps.getLongitude();
			myLocation = new LatLng(latitude, longitude);
		}

		MarkerOptions mkOption = new MarkerOptions()
				.position(myLocation)
				.title("My location !")
				.snippet("")
				.icon(BitmapDescriptorFactory
						.fromResource(R.drawable.ic_marker_my_place));

		map = ((MapFragment) getFragmentManager().findFragmentById(
				R.id.mapPlaceEdit)).getMap();

		// add maker to map
		map.addMarker(mkOption);
		map.moveCamera(CameraUpdateFactory.newLatLngZoom(myLocation, 20));

		// Zoom in, animating the camera.
		map.animateCamera(CameraUpdateFactory.zoomTo(15), 2000, null);

		map.setOnMarkerClickListener(onMarkerClick);

		if (mIsGoogle) {
			// display dialog add
			LatLng point = new LatLng(myPlace.locationx, myPlace.locationy);
			String name = myPlace.placename;
			String address = myPlace.description;
			final Dialog dl = new Dialog(PlaceAddActivity.this);
			// dl.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE);
			dl.requestWindowFeature(Window.FEATURE_NO_TITLE);
			View v = createViewDialogAddNewPlace(PlaceAddActivity.this,
					CLICK_MARKER, mIsGoogle, name, address, point, map, dl);
			dl.setContentView(v);

			MarkerOptions mkOption1 = new MarkerOptions()
					.position(point)
					.title(name)
					.snippet(address)
					.icon(BitmapDescriptorFactory
							.fromResource(R.drawable.ic_marker_search));
			map.addMarker(mkOption1);
			map.moveCamera(CameraUpdateFactory.newLatLngZoom(point, 20));
			// Zoom in, animating the camera.
			map.animateCamera(CameraUpdateFactory.zoomTo(15), 2000, null);
			dl.show();
		}

		map.setOnMapClickListener(new OnMapClickListener() {

			public void onMapClick(LatLng point) {
				// TODO Auto-generated method stub
				final Dialog dl = new Dialog(PlaceAddActivity.this);
				dl.requestWindowFeature(Window.FEATURE_NO_TITLE);
				View v = createViewDialogAddNewPlace(PlaceAddActivity.this,
						CLICK_MAP, mIsGoogle, "", "", point, map, dl);
				dl.setContentView(v);
				dl.show();
			}
		});

		mImageViewMyPlace.setOnClickListener(new OnClickListener() {

			public void onClick(View arg0) {
				// TODO Auto-generated method stub
				map.moveCamera(CameraUpdateFactory
						.newLatLngZoom(myLocation, 20));
				// Zoom in, animating the camera.
				map.animateCamera(CameraUpdateFactory.zoomTo(15), 2000, null);
			}
		});

		mImageViewSearch.setOnClickListener(new OnClickListener() {

			public void onClick(View arg0) {
				// TODO Auto-generated method stub
				if (!mEditTextEnable) {
					mEditTextSearch.setVisibility(View.VISIBLE);
					mEditTextEnable = true;
				} else {
					if (mEditTextSearch.getText().toString().trim().equals("")) {
						Toast.makeText(getBaseContext(),
								getString(R.string.input_not_null),
								Toast.LENGTH_LONG).show();
					} else {
						searchPlace();
					}
				}

			}
		});
	}

	OnMarkerClickListener onMarkerClick = new OnMarkerClickListener() {

		public boolean onMarkerClick(Marker marker) {
			// TODO Auto-generated method stub
			LatLng point = new LatLng(marker.getPosition().latitude,
					marker.getPosition().longitude);
			String name = marker.getTitle();
			String address = marker.getSnippet();
			final Dialog dl = new Dialog(PlaceAddActivity.this);
			dl.requestWindowFeature(Window.FEATURE_NO_TITLE);
			View v = createViewDialogAddNewPlace(PlaceAddActivity.this,
					CLICK_MARKER, mIsGoogle, name, address, point, map, dl);
			dl.setContentView(v);
			dl.show();
			return false;
		}
	};

	/**
	 * Event search by Keyword
	 */

	private OnKeyListener searchTextListener = new OnKeyListener() {
		public boolean onKey(View v, int keyCode, KeyEvent event) {
			if (keyCode == KeyEvent.KEYCODE_ENTER
					&& event.getAction() == KeyEvent.ACTION_DOWN) {
				// execute search and zoom to that place
				if (mEditTextSearch.getText().toString().trim().equals("")) {
					Toast.makeText(getBaseContext(),
							getString(R.string.input_not_null),
							Toast.LENGTH_LONG).show();
				} else {
					searchPlace();
				}

				return false;
			}
			return false;
		}
	};

	/**
	 * create view dialog edit
	 * 
	 * @param context
	 * @return
	 */
	ImageView imageViewAddImage;

	public View createViewDialogAddNewPlace(final Context context,
			int typeHasSearch, boolean isGoogle, String name, String address,
			final LatLng position, final GoogleMap map, final Dialog dialog) {
		LayoutInflater mLayoutInflater = (LayoutInflater) context
				.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
		View view = mLayoutInflater.inflate(R.layout.dialog_maker_edit, null);
		final EditText editTextName = (EditText) view
				.findViewById(R.id.editTextPlaceName);
		final Spinner spinnerCategory = (Spinner) view
				.findViewById(R.id.spinnerPlaceCategory);
		final EditText editTextAddress = (EditText) view
				.findViewById(R.id.editTextPlaceAddress);
		final EditText editTextMobile = (EditText) view
				.findViewById(R.id.editTextPlaceMobile);
		final EditText editTextMobilePhone = (EditText) view
				.findViewById(R.id.editTextPlaceMobilePhone);
		final EditText editTextFax = (EditText) view
				.findViewById(R.id.editTextPlaceFax);
		final EditText editTextVideo = (EditText) view
				.findViewById(R.id.editTextPlaceVideo);
		final EditText editTextWebsite = (EditText) view
				.findViewById(R.id.editTextPlaceWebsite);
		final EditText editTextEmail = (EditText) view
				.findViewById(R.id.editTextPlaceEmail);

		final EditText editTextInfor = (EditText) view
				.findViewById(R.id.editTextPlaceInfor);
		imageViewAddImage = (ImageView) view
				.findViewById(R.id.imageViewPlaceAddImage);
		Button buttonAdd = (Button) view.findViewById(R.id.buttonPlaceAdd);

		mLayoutBelow = (LinearLayout) view.findViewById(R.id.layoutBelow);

		mLayoutRoot.getViewTreeObserver().addOnGlobalLayoutListener(
				new OnGlobalLayoutListener() {
					public void onGlobalLayout() {
						int heightDiff = mLayoutRoot.getRootView().getHeight()
								- mLayoutRoot.getHeight();
						if (heightDiff > 100) { // if more than 100 pixels, its
												// probably a keyboard...
							mLayoutBelow.setVisibility(View.VISIBLE);
						} else {
							mLayoutBelow.setVisibility(View.GONE);
						}
					}
				});

		if (typeHasSearch == CLICK_MARKER) {
			editTextName.setText(name);
			editTextAddress.setText(Utilities.getInstance().getValueByType(
					Constants.TYPE_ADDRESS, address));
			editTextInfor.setText(Utilities.getInstance().getValueByType(
					Constants.TYPE_INFO, address));
			editTextMobile.setText(Utilities.getInstance().getValueByType(
					Constants.TYPE_MOBILE, address));
			editTextMobilePhone.setText(Utilities.getInstance().getValueByType(
					Constants.TYPE_MOBILE_PHONE, address));
			editTextEmail.setText(Utilities.getInstance().getValueByType(
					Constants.TYPE_EMAIL, address));
			editTextFax.setText(Utilities.getInstance().getValueByType(
					Constants.TYPE_FAX, address));
			editTextWebsite.setText(Utilities.getInstance().getValueByType(
					Constants.TYPE_WEBSITE, address));
			editTextVideo.setText(Utilities.getInstance().getValueByType(
					Constants.TYPE_VIDEO, address));
		}

		ArrayList<Category> arrCategory = FgCategory.items;
		ArrayList<String> arrList = new ArrayList<String>();
		for (int i = 0; i < arrCategory.size(); i++) {
			arrList.add(arrCategory.get(i).name);
		}

		ArrayList<String> valuesCategory = new ArrayList<String>();
		// check is vietnamese or english..default is english
		boolean isEn = CommonUtils.getBooleanSetting(this, Constants.IS_EN,
				false);
		if (isEn) {
			valuesCategory = Utilities.getInstance().getValueCategory(arrList,
					Constants.LANGUAGE_EN);
		} else {
			valuesCategory = Utilities.getInstance().getValueCategory(arrList,
					Constants.LANGUAGE_VN);
		}

		ArrayAdapter<String> adp = new ArrayAdapter<String>(context,
				android.R.layout.simple_spinner_item, android.R.id.text1,
				valuesCategory);

		spinnerCategory.setAdapter(adp);
		if (isGoogle) {
			spinnerCategory.setSelection(categoryID - 1);
		}

		imageViewAddImage.setOnClickListener(new OnClickListener() {

			public void onClick(View arg0) {
				// TODO Auto-generated method stub
				// go to gallery folder and add to
				Intent i = new Intent(
						Intent.ACTION_PICK,
						android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
				startActivityForResult(i, RESULT_LOAD_IMAGE);
			}
		});

		buttonAdd.setOnClickListener(new OnClickListener() {

			public void onClick(View arg0) {
				// TODO Auto-generated method stub
				InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
				imm.hideSoftInputFromWindow(editTextName.getWindowToken(), 0);

				if (!Utilities.getInstance().checkInputFormat(
						editTextName.getText().toString())) {
					Toast.makeText(
							context,
							context.getResources().getString(
									R.string.message_alert_input_blank),
							Toast.LENGTH_LONG).show();
				} else if (!editTextEmail.getText().toString().trim()
						.equals("")) {
					if (!Utilities.validateEmail(editTextEmail.getText()
							.toString().trim())) {
						Toast.makeText(
								context,
								context.getResources().getString(
										R.string.message_email_error),
								Toast.LENGTH_LONG).show();
					}
				} else {
					// operation edit place
					// execute api to edit place
					dialog.dismiss();

					float latitude = Float.parseFloat(String
							.valueOf(position.latitude));
					float longitude = Float.parseFloat(String
							.valueOf(position.longitude));
					String nameEdit = editTextName.getText().toString()
							.replace("*", "");

					String addressEdit = editTextAddress.getText().toString()
							.replace("*", "");
					String mobileEdit = editTextMobile.getText().toString()
							.replace("*", "");
					String mobilePhoneEdit = editTextMobilePhone.getText()
							.toString().replace("*", "");
					String faxEdit = editTextFax.getText().toString()
							.replace("*", "");
					String videoEdit = editTextVideo.getText().toString()
							.replace("*", "");
					String websiteEdit = editTextWebsite.getText().toString()
							.replace("*", "");
					String emailEdit = editTextEmail.getText().toString()
							.replace("*", "");
					String inforEdit = editTextInfor.getText().toString()
							.replace("*", "");
					int categoryID = spinnerCategory.getSelectedItemPosition() + 1;
					String time = DateFormat.format("MM,dd,yyyy ",
							new Date().getTime()).toString();
					String imageString = "";
					if (!pathImage.equals("")) {
						try {
							imageString = Utilities.getInstance()
									.getStringBase64FromImage(pathImage);
						} catch (FileNotFoundException e) {
							// TODO Auto-generated catch block
							imageString = "";
							e.printStackTrace();
						}
					}

					String description = Utilities.getInstance()
							.getDescriptionValue(inforEdit, addressEdit,
									mobileEdit, mobilePhoneEdit, faxEdit,
									videoEdit, websiteEdit, emailEdit);

					Place placeAdd = new Place(latitude, longitude, nameEdit,
							description, categoryID, "", imageString, time,
							time);

					addPlaceToServer(placeAdd, dialog);
				}

			}
		});

		return view;
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		if (requestCode == RESULT_LOAD_IMAGE && resultCode == RESULT_OK
				&& null != data) {
			Uri selectedImage = data.getData();
			String[] filePathColumn = { MediaStore.Images.Media.DATA };
			Cursor cursor = getContentResolver().query(selectedImage,
					filePathColumn, null, null, null);
			cursor.moveToFirst();
			int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
			String picturePath = cursor.getString(columnIndex);
			pathImage = picturePath;
			cursor.close();
			imageViewAddImage.setImageBitmap(BitmapFactory
					.decodeFile(picturePath));
		}
	}

	/**
	 * Search place from goole api
	 */
	private void searchPlace() {
		new GetDataTask(PlaceAddActivity.this, new IGetDataTask() {
			String api1 = "https://maps.googleapis.com/maps/api/place/textsearch/json?query=";
			String api2 = "&sensor=true&key=" + Constants.BROWSER_KEY;

			@Override
			public boolean doInBackGround() throws Exception {
				String searchStr = mEditTextSearch.getText().toString();
				searchStr = searchStr.replace(' ', '+');
				String api = api1 + searchStr + api2;
				String response = CustomHttpClient.executeHttpGet(api);
				arrPlaces = GoogleMapUtil.getInstance().initGooglePlace(
						response);
				return false;
			}

			@Override
			public void onPostExecute(boolean result) throws Exception {
				super.onPostExecute(result);
				try {
					if (arrPlaces == null) {
						Toast.makeText(getBaseContext(),
								getString(R.string.empty_by_error),
								Toast.LENGTH_LONG).show();
					} else {
						// add place found to google map
						for (int i = 0; i < arrPlaces.size(); i++) {
							MarkerOptions mkOption = new MarkerOptions();
							mkOption.position(new LatLng(
									arrPlaces.get(i).locationx, arrPlaces
											.get(i).locationy));
							mkOption.title(arrPlaces.get(i).placename);
							mkOption.snippet(arrPlaces.get(i).description);
							mkOption.icon(BitmapDescriptorFactory
									.fromResource(R.drawable.ic_marker_search));
							map.addMarker(mkOption);

							if (i == 0) {
								// zoom to the first place
								map.moveCamera(CameraUpdateFactory.newLatLngZoom(
										new LatLng(arrPlaces.get(0).locationx,
												arrPlaces.get(0).locationy), 20));
								// Zoom in, animating the camera.
								map.animateCamera(
										CameraUpdateFactory.zoomTo(15), 2000,
										null);
							}
						}
					}
				} catch (Exception e) {
				}

			}

		}, false).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);

	}

	/**
	 * @param place
	 */
	String resultFromServer;

	private void addPlaceToServer(final Place place, final Dialog dialog) {
		new GetDataTask(PlaceAddActivity.this, new IGetDataTask() {

			@Override
			public boolean doInBackGround() throws Exception {
				resultFromServer = ServerAPI.SetUserPlaces(CommonUtils
						.getStringSetting(PlaceAddActivity.this,
								Constants.TOKEN_ID, null), place.locationx,
						place.locationy, place.placename, place.description,
						place.image, place.categoryid);
				// cho nay tra ve flag true or false and unique_id if have
				Log.e("TokenID", CommonUtils.getStringSetting(
						PlaceAddActivity.this, Constants.TOKEN_ID, null));
				Log.e("localx", place.locationx + "");
				Log.e("localy", place.locationy + "");
				Log.e("placeName", place.placename);
				Log.e("description", place.description);
				Log.e("image", place.image);
				Log.e("category", place.categoryid + "");

				if (resultFromServer.contains("True")) {
					return true;
				} else {
					return false;
				}

			}

			@Override
			public void onPostExecute(boolean result) throws Exception {
				super.onPostExecute(result);
				if (result) {
					// If add success,get a place with infor input and unique_id
					// get from server and add to array place available in map
					String uniqueID = Utilities.getInstance().getUniqueID(
							resultFromServer);
					Place newPlace = new Place(place.locationx,
							place.locationy, place.placename,
							place.description, place.categoryid, uniqueID,
							place.image, place.created_at, place.updated_at);
					arrPlaceAddAvailable.add(newPlace);

					Toast.makeText(getBaseContext(),
							getString(R.string.add_success), Toast.LENGTH_LONG)
							.show();

					MarkerOptions mkOptionAdd = new MarkerOptions()
							.position(
									new LatLng(place.locationx, place.locationy))
							.title(place.placename)
							.snippet(place.description)
							.icon(Utilities.getInstance()
									.getBitmapDescriptionFromType(
											place.categoryid));
					map.addMarker(mkOptionAdd);
				} else {
					Log.e("add", "false");
				}
			}

		}, true).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
	}

	/**
	 * @param place
	 */
	private void editPlaceToServer(final Place place, final Dialog dialog) {
		new GetDataTask(PlaceAddActivity.this, new IGetDataTask() {

			@Override
			public boolean doInBackGround() throws Exception {
				boolean resultFlag = ServerAPI.EditUserPlaces(CommonUtils
						.getStringSetting(PlaceAddActivity.this,
								Constants.TOKEN_ID, null), place.uniqueid,
						place.locationx, place.locationy, place.placename,
						place.description, place.image, place.categoryid);
				return resultFlag;
			}

			@Override
			public void onPostExecute(boolean result) throws Exception {
				super.onPostExecute(result);

				String tokenID = CommonUtils.getStringSetting(
						PlaceAddActivity.this, Constants.TOKEN_ID, "");
				Log.e("TokenID", tokenID);

				if (result) {
					// placeEditFinish=place;
					// isEdited=true;
					// map.clear();
					// mkOption1 = new MarkerOptions()
					// .position(new LatLng(placeEditFinish.locationx,
					// placeEditFinish.locationy))
					// .title(place.placename)
					// .snippet(place.description)
					// .icon(Utilities.getInstance().getBitmapDescriptionFromType(
					// place.categoryid));
					// map.addMarker(mkOption1);
					// Toast.makeText(getBaseContext(),
					// getString(R.string.message_edit_success),
					// Toast.LENGTH_LONG).show();
					dialog.dismiss();
				}
			}

		}, true).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);

	}

	@Override
	public void onConfigurationChanged(Configuration newConfig) {
		super.onConfigurationChanged(newConfig);
	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK) {
			// return list google place or list unapproved,approved
			if (mIsGoogle) {
				PlaceAddActivity.this.finish();
			} else {
				// go to my place unapproved
				Intent i = new Intent(PlaceAddActivity.this,
						ListPlaceActivity.class);
				i.putExtra(BundleKeys.IS_USER_PLACE, true);
				startActivity(i);
				PlaceAddActivity.this.finish();
			}
			return true;
		}
		return super.onKeyDown(keyCode, event);
	}

}